package com.x.service.transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.x.dao.ConfigurationDAO;
import com.x.dao.ShipmentsDAO;
import com.x.dao.TransitTimeDAO;
import com.x.model.Configuration;
import com.x.model.Shipments;

@Component("shipmentsService")
public class ShipmentsService {
	@Autowired
	private ShipmentsDAO shipmentsDAO;
	@Autowired
	private TransitTimeDAO transitTimeDAO;
	@Autowired
	private ConfigurationDAO configurationDAO;

	public boolean upload(MultipartFile file) {
		byte[] buffer;
		try {
			buffer = file.getBytes();
			String contents = new String(buffer, "UTF-8");
			String[] contentList = contents.split("\\n|\\r\\n|\\r|\\n\\r");
			List<String[]> results = new ArrayList<>();
			BigDecimal sum = new BigDecimal(0);
			for (String content : contentList) {
				String[] lists = content.split("\\t");
				BigDecimal shipmentsNum = new BigDecimal(lists[5]);
				sum = sum.add(shipmentsNum);
				results.add(lists);
			}
			List<Shipments> shipments = new ArrayList<>();
			List<Configuration> configs = new ArrayList<>();
			Timestamp ts = new Timestamp(System.currentTimeMillis());
			for (String[] result : results) {
				Shipments shipment = new Shipments();
				shipment.setFc(result[0]);
				shipment.setShipMethod(result[1]);
				shipment.setProvince(result[2]);
				shipment.setCity(result[3]);
				shipment.setDistrict(result[4]);

				BigDecimal shipNum = new BigDecimal(result[5]);
				BigDecimal percent = shipNum.divide(sum, 8,
						BigDecimal.ROUND_HALF_UP);
				shipment.setShipments(percent);
				shipments.add(shipment);

				int tt = transitTimeDAO.getTT(result[0], result[1], result[2],
						result[3], result[4]);
				if (tt >= 0) {
					Configuration config = new Configuration();
					config.setFc(result[0]);
					config.setShipMethod(result[1]);
					config.setProvince(result[2]);
					config.setCity(result[3]);
					config.setDistrict(result[4]);
					config.setShipments(percent);
					config.setTt(tt);
					config.setCreatetime(ts);
					configs.add(config);
				}

			}
			shipmentsDAO.trancate();
			shipmentsDAO.upload(shipments);
			configurationDAO.upload(configs);

		} catch (IOException e) {
			e.printStackTrace();
		}
		return true;
	}
}
